package org.csu.jpetstore_users_backend_pj.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.csu.jpetstore_users_backend_pj.dto.GiteeUser;
import org.csu.jpetstore_users_backend_pj.mapper.AccountMapper;
import org.csu.jpetstore_users_backend_pj.service.GiteeAccessService;
import org.csu.jpetstore_users_backend_pj.util.RequestFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Optional;

@Service
public class GiteeAccessServiceImpl implements GiteeAccessService {

    private final OkHttpClient client;
    private final RequestFactory requestFactory;
    private final ObjectMapper objectMapper;
    @Autowired
    private AccountMapper accountMapper;

    @Value("${gitee.client.id}")
    private String clientId;

    @Value("${gitee.client.secret}")
    private String clientSecret;

    @Value("${gitee.redirect.uri}")
    private String redirectUri;

    // 通过构造函数注入 OkHttpClient 和 RequestFactory
    public GiteeAccessServiceImpl(OkHttpClient client, RequestFactory requestFactory, ObjectMapper objectMapper) {
        this.client = client;
        this.requestFactory = requestFactory;
        this.objectMapper = objectMapper;
    }

    @Override
    public Optional<String> getToken(String code) {
        Request request = requestFactory.createTokenRequest(code, clientId, clientSecret, redirectUri);

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful() || response.body() == null) {
                return Optional.empty();
            }
            // 使用 Jackson 解析 JSON
            JsonNode jsonNode = objectMapper.readTree(response.body().string());
            return Optional.ofNullable(jsonNode.get("access_token").asText());
        } catch (IOException e) {
            return Optional.empty();
        }
    }

    @Override
    public Optional<GiteeUser> getUser(String accessToken) {
        Request request = requestFactory.createUserRequest(accessToken);

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful() || response.body() == null) {
                return Optional.empty();
            }
            return Optional.ofNullable(objectMapper.readValue(response.body().string(), GiteeUser.class));
        } catch (IOException e) {
            return Optional.empty();
        }
    }
    @Override
    public void saveAccessToken(String giteeId,String accessToken){
        if (accountMapper.countByGiteeId(giteeId) > 0) {
            accountMapper.updateGiteeTokenByGiteeId(giteeId, accessToken);
        }
    }
    @Override
    public void revokeToken(String giteeId){
        String accessToken = getAccessTokenFromDB(giteeId);
        if (accessToken != null) {
            accountMapper.updateGiteeTokenByGiteeId(giteeId,null);
        } else {
            System.err.println("未能获取到 accessToken，撤销失败！");
        }
    }
    @Override
    public String getAccessTokenFromDB(String giteeId){
        return accountMapper.getTokenByGiteeId(giteeId);
    }
}

